package vip.sweet.sys.modular.login.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import vip.sweet.common.enums.ResponseEnum;
import vip.sweet.common.response.CommonResponse;
import vip.sweet.common.utils.IPUtils;
import vip.sweet.common.utils.JwtUtil;
import vip.sweet.common.utils.MD5Util;
import vip.sweet.common.utils.RedisUtil;
import vip.sweet.sys.modular.login.entity.LoginMonitor;
import vip.sweet.sys.modular.login.params.LoginParams;
import vip.sweet.sys.modular.login.service.LoginMonitorService;
import vip.sweet.sys.modular.login.service.impl.SecurityUserDetailImpl;
import vip.sweet.sys.modular.user.entity.SecurityUser;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author tianlianyin
 * @Date 2024/11/9
 */
@Tag(name = "后台登录控制器")
@RestController
@RequestMapping("/sys")
@Slf4j
public class LoginController {
    @Resource
    private SecurityUserDetailImpl securityUserDetailImpl;
    @Resource
    private JwtUtil jwtUtil;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private LoginMonitorService loginMonitorService;

    @PostMapping("/login")
    @Operation(summary = "账号密码登录接口")
    public CommonResponse login(@RequestBody @Validated LoginParams loginParams, HttpServletRequest request) {
        SecurityUser securityUser = (SecurityUser) securityUserDetailImpl.loadUserByUsername(loginParams.getUsername());
        if (securityUser == null)
            return CommonResponse.error(ResponseEnum.ERROR, "用户不存在");
        if (!MD5Util.checkPassword(loginParams.getPassword(), securityUser.getPassword()))
            return CommonResponse.error(ResponseEnum.ERROR, "用户密码错误");
        String token = jwtUtil.generateToken(securityUser.getUsername());
        redisUtil.set("token-" + token, token, JwtUtil.EXPIRE, TimeUnit.MINUTES);
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("username", securityUser.getUsername());
        String ipAddress = IPUtils.getIpAddress(request);
        String cityInfo;
        try {
            cityInfo = IPUtils.getCityInfo(ipAddress);
        } catch (Exception e) {
            log.error("获取ip归属地失败", e);
            throw new RuntimeException(e);
        }
        loginMonitorService.save(
                LoginMonitor.builder()
                        .userId(securityUser.getUserId())
                        .userName(securityUser.getUsername())
                        .loginIp(ipAddress)
                        .loginIpAttribute(cityInfo)
                        .loginTime(new Date())
                        .build()
        );
        return CommonResponse.success(map);
    }
}
